<template>
  <div class="data-analysis">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>数据分析</h2>
        <p class="header-desc">平台运营数据分析与监控</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" size="40"><Loading /></el-icon>
      <p>数据加载中...</p>
    </div>

    <!-- 主要内容 -->
    <div v-else>
      <!-- KPI 指标卡片 -->
      <div class="kpi-section">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-card class="kpi-card" shadow="hover">
              <div class="kpi-content">
                <div class="kpi-icon orders">
                  <el-icon size="32"><Document /></el-icon>
                </div>
                <div class="kpi-info">
                  <div class="kpi-value">{{ overviewData.totalOrders || 0 }}</div>
                  <div class="kpi-label">总订单数</div>
                  <div class="kpi-trend">
                    <span :class="['trend-text', overviewData.ordersTrend >= 0 ? 'positive' : 'negative']">
                      <el-icon><CaretTop v-if="overviewData.ordersTrend >= 0" /><CaretBottom v-else /></el-icon>
                      {{ Math.abs(overviewData.ordersTrend || 0).toFixed(1) }}%
                    </span>
                    <span class="trend-period">较上期</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="kpi-card" shadow="hover">
              <div class="kpi-content">
                <div class="kpi-icon revenue">
                  <el-icon size="32"><Money /></el-icon>
                </div>
                <div class="kpi-info">
                  <div class="kpi-value">¥{{ formatNumber(overviewData.totalRevenue || 0) }}</div>
                  <div class="kpi-label">总收入</div>
                  <div class="kpi-trend">
                    <span :class="['trend-text', overviewData.revenueTrend >= 0 ? 'positive' : 'negative']">
                      <el-icon><CaretTop v-if="overviewData.revenueTrend >= 0" /><CaretBottom v-else /></el-icon>
                      {{ Math.abs(overviewData.revenueTrend || 0).toFixed(1) }}%
                    </span>
                    <span class="trend-period">较上期</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="kpi-card" shadow="hover">
              <div class="kpi-content">
                <div class="kpi-icon weight">
                  <el-icon size="32"><ScaleToOriginal /></el-icon>
                </div>
                <div class="kpi-info">
                  <div class="kpi-value">{{ formatNumber(overviewData.totalWeight || 0) }}kg</div>
                  <div class="kpi-label">回收重量</div>
                  <div class="kpi-trend">
                    <span :class="['trend-text', overviewData.weightTrend >= 0 ? 'positive' : 'negative']">
                      <el-icon><CaretTop v-if="overviewData.weightTrend >= 0" /><CaretBottom v-else /></el-icon>
                      {{ Math.abs(overviewData.weightTrend || 0).toFixed(1) }}%
                    </span>
                    <span class="trend-period">较上期</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="kpi-card" shadow="hover">
              <div class="kpi-content">
                <div class="kpi-icon customers">
                  <el-icon size="32"><User /></el-icon>
                </div>
                <div class="kpi-info">
                  <div class="kpi-value">{{ overviewData.activeCustomers || 0 }}</div>
                  <div class="kpi-label">活跃用户</div>
                  <div class="kpi-trend">
                    <span :class="['trend-text', overviewData.customersTrend >= 0 ? 'positive' : 'negative']">
                      <el-icon><CaretTop v-if="overviewData.customersTrend >= 0" /><CaretBottom v-else /></el-icon>
                      {{ Math.abs(overviewData.customersTrend || 0).toFixed(1) }}%
                    </span>
                    <span class="trend-period">较上期</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 统计数据卡片 -->
      <el-row :gutter="24" style="margin-top: 24px;">
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">站点统计</span>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-item">
                <span class="stats-label">总站点数</span>
                <span class="stats-value">{{ overviewData.totalStations || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">活跃站点</span>
                <span class="stats-value active">{{ stationsStats.active || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">繁忙站点</span>
                <span class="stats-value warning">{{ stationsStats.busy || 0 }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">用户统计</span>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-item">
                <span class="stats-label">客户总数</span>
                <span class="stats-value">{{ overviewData.activeCustomers || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">站长总数</span>
                <span class="stats-value">{{ userStats.stationManagers || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">今日活跃</span>
                <span class="stats-value active">{{ userStats.todayActive || 0 }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">物品统计</span>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-item">
                <span class="stats-label">物品种类</span>
                <span class="stats-value">{{ itemStats.totalCategories || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">启用物品</span>
                <span class="stats-value active">{{ itemStats.activeItems || 0 }}</span>
              </div>
              <div class="stats-item">
                <span class="stats-label">总物品数</span>
                <span class="stats-value">{{ itemStats.totalItems || 0 }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 物品分类统计 -->
      <el-row :gutter="24" style="margin-top: 24px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">物品分类回收统计</span>
              </div>
            </template>
            <div class="category-list">
              <div v-if="categoryStats.length === 0" class="empty-data">
                <el-empty description="暂无数据" :image-size="80" />
              </div>
              <div v-else class="category-item" v-for="category in categoryStats" :key="category.name">
                <div class="category-info">
                  <span class="category-name">{{ category.name }}</span>
                  <span class="category-count">{{ category.count }}件</span>
                </div>
                <el-progress 
                  :percentage="category.percentage" 
                  :color="getCategoryColor(category.name)"
                  :stroke-width="12"
                />
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">站点排行榜（按订单量）</span>
              </div>
            </template>
            <div class="ranking-list">
              <div v-if="stationRanking.length === 0" class="empty-data">
                <el-empty description="暂无数据" :image-size="80" />
              </div>
              <div v-else class="ranking-item" v-for="(station, index) in stationRanking" :key="station.id">
                <div class="rank-badge" :class="getRankClass(index)">{{ index + 1 }}</div>
                <div class="station-info">
                  <div class="station-name">{{ station.name }}</div>
                  <div class="station-address">{{ station.address }}</div>
                </div>
                <div class="station-stats">
                  <div class="stat-value">{{ station.orderCount || 0 }}</div>
                  <div class="stat-label">订单</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 订单状态分布 -->
      <el-row :gutter="24" style="margin-top: 24px;">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">订单状态分布</span>
              </div>
            </template>
            <div class="status-grid">
              <div class="status-card" v-for="status in orderStatusStats" :key="status.name">
                <div class="status-icon" :style="{ background: status.color }">
                  <el-icon size="24"><Document /></el-icon>
                </div>
                <div class="status-info">
                  <div class="status-count">{{ status.count }}</div>
                  <div class="status-label">{{ status.label }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document,
  Money,
  ScaleToOriginal,
  User,
  CaretTop,
  CaretBottom,
  Loading
} from '@element-plus/icons-vue'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const overviewData = ref({
  totalOrders: 0,
  totalRevenue: 0,
  totalWeight: 0,
  activeCustomers: 0,
  totalStations: 0,
  ordersTrend: 0,
  revenueTrend: 0,
  weightTrend: 0,
  customersTrend: 0
})
const stationsStats = ref({
  total: 0,
  active: 0,
  busy: 0,
  closed: 0
})
const userStats = ref({
  stationManagers: 0,
  todayActive: 0
})
const itemStats = ref({
  totalCategories: 0,
  activeItems: 0,
  totalItems: 0
})
const categoryStats = ref([])
const stationRanking = ref([])
const orderStatusStats = ref([
  { name: 'pending', label: '待确认', count: 0, color: 'linear-gradient(135deg, #ffd89b 0%, #f59e0b 100%)' },
  { name: 'confirmed', label: '已确认', count: 0, color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
  { name: 'in_progress', label: '进行中', count: 0, color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' },
  { name: 'completed', label: '已完成', count: 0, color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)' },
  { name: 'cancelled', label: '已取消', count: 0, color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' }
])

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0'
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取分类颜色
const getCategoryColor = (categoryName) => {
  const colors = {
    '纸类': '#409EFF',
    '塑料': '#67C23A',
    '金属': '#E6A23C',
    '玻璃': '#F56C6C',
    '电子产品': '#909399'
  }
  return colors[categoryName] || '#409EFF'
}

// 获取排名样式
const getRankClass = (index) => {
  if (index === 0) return 'rank-first'
  if (index === 1) return 'rank-second'
  if (index === 2) return 'rank-third'
  return ''
}

// 获取总体数据
const fetchOverviewData = async () => {
  try {
    const data = await api.analytics.getOverview()
    overviewData.value = data
  } catch (error) {
    console.error('获取总体数据失败:', error)
  }
}

// 获取站点统计
const fetchStationsStats = async () => {
  try {
    const data = await api.analytics.getStationsStats()
    stationsStats.value = data
  } catch (error) {
    console.error('获取站点统计失败:', error)
  }
}

// 获取用户统计
const fetchUserStats = async () => {
  try {
    // 获取站长数量
    const usersResponse = await api.users.getUsers({ 
      page: 1, 
      pageSize: 1000, 
      role: 'station_manager' 
    })
    userStats.value.stationManagers = usersResponse.total || 0
    userStats.value.todayActive = Math.floor(userStats.value.stationManagers * 0.6) // 模拟今日活跃
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 获取物品统计
const fetchItemStats = async () => {
  try {
    const response = await api.items.getItems({ page: 1, pageSize: 1000 })
    itemStats.value.totalItems = response.total || 0
    itemStats.value.activeItems = response.list?.filter(item => item.status === 'active').length || 0
    
    // 计算分类数量
    const categories = new Set(response.list?.map(item => item.category) || [])
    itemStats.value.totalCategories = categories.size
    
    // 统计每个分类的数量
    const categoryCount = {}
    response.list?.forEach(item => {
      categoryCount[item.category] = (categoryCount[item.category] || 0) + 1
    })
    
    // 转换为数组并计算百分比
    const total = response.total || 1
    categoryStats.value = Object.entries(categoryCount).map(([name, count]) => ({
      name,
      count,
      percentage: Math.round((count / total) * 100)
    })).sort((a, b) => b.count - a.count).slice(0, 5) // 只显示前5个
  } catch (error) {
    console.error('获取物品统计失败:', error)
  }
}

// 获取站点排行
const fetchStationRanking = async () => {
  try {
    // 调用真实的站点排行API，从orders表统计每个站点的订单数量
    const data = await api.analytics.getStationsRanking()
    stationRanking.value = data || []
  } catch (error) {
    console.error('获取站点排行失败:', error)
  }
}

// 获取订单状态统计
const fetchOrderStatusStats = async () => {
  try {
    // 调用真实的后端API获取订单状态统计
    const data = await api.analytics.getOrdersStatusStats()
    
    // 更新每个状态的计数
    if (data && Array.isArray(data)) {
      data.forEach(item => {
        const statusItem = orderStatusStats.value.find(s => s.name === item.name)
        if (statusItem) {
          statusItem.count = item.count
        }
      })
    }
  } catch (error) {
    console.error('获取订单状态统计失败:', error)
  }
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchOverviewData(),
      fetchStationsStats(),
      fetchUserStats(),
      fetchItemStats(),
      fetchStationRanking(),
      fetchOrderStatusStats()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.data-analysis {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header .header-left h2 {
  margin: 0 0 8px 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.page-header .header-left .header-desc {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.page-header .header-actions {
  display: flex;
  gap: 12px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  background: white;
  border-radius: 8px;
}

.loading-container p {
  margin-top: 16px;
  font-size: 16px;
  color: #909399;
}

.kpi-section .kpi-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.kpi-section .kpi-card:hover {
  transform: translateY(-4px);
}

.kpi-section .kpi-card :deep(.el-card__body) {
  padding: 24px;
}

.kpi-section .kpi-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.kpi-section .kpi-icon {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  flex-shrink: 0;
}

.kpi-section .kpi-icon.orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.kpi-section .kpi-icon.revenue {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.kpi-section .kpi-icon.weight {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.kpi-section .kpi-icon.customers {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.kpi-section .kpi-info {
  flex: 1;
}

.kpi-section .kpi-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.kpi-section .kpi-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.kpi-section .kpi-trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.kpi-section .kpi-trend .trend-text {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.kpi-section .kpi-trend .trend-text.positive {
  color: #67c23a;
}

.kpi-section .kpi-trend .trend-text.negative {
  color: #f56c6c;
}

.kpi-section .kpi-trend .trend-period {
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 12px 0;
}

.stats-content .stats-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stats-content .stats-item .stats-label {
  font-size: 15px;
  color: #606266;
}

.stats-content .stats-item .stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-content .stats-item .stats-value.active {
  color: #67c23a;
}

.stats-content .stats-item .stats-value.warning {
  color: #e6a23c;
}

.category-list {
  padding: 12px 0;
}

.category-item {
  margin-bottom: 24px;
}

.category-item:last-child {
  margin-bottom: 0;
}

.category-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 15px;
}

.category-name {
  color: #303133;
  font-weight: 500;
}

.category-count {
  color: #606266;
}

.ranking-list {
  padding: 12px 0;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  margin-bottom: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.ranking-item:hover {
  background: #e8f4ff;
  transform: translateX(4px);
}

.ranking-item:last-child {
  margin-bottom: 0;
}

.rank-badge {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #909399;
  color: white;
  font-size: 16px;
  font-weight: 600;
  flex-shrink: 0;
}

.rank-badge.rank-first {
  background: linear-gradient(135deg, #ffd89b 0%, #f59e0b 100%);
}

.rank-badge.rank-second {
  background: linear-gradient(135deg, #d4d4d8 0%, #71717a 100%);
}

.rank-badge.rank-third {
  background: linear-gradient(135deg, #fed7aa 0%, #d97706 100%);
}

.station-info {
  flex: 1;
}

.station-name {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.station-address {
  font-size: 13px;
  color: #909399;
}

.station-stats {
  text-align: center;
  padding: 0 12px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
  padding: 12px 0;
}

.status-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.status-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.status-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  color: white;
  margin-bottom: 12px;
}

.status-info {
  text-align: center;
}

.status-count {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

.empty-data {
  padding: 20px;
  text-align: center;
}

:deep(.el-card) {
  border-radius: 8px;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-progress__text) {
  font-size: 14px !important;
  font-weight: 500;
}
</style>
